package rs.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import rs.domain.Track;

/* Classe responsabile del parsing di un JSON relativo ai brani migliori per un tag */
public class RecommendedTrackParser {

	public List<Track> parse(String response) {
		List<Track> rec_track = new ArrayList<Track>();
		if (!response.substring(2,7).equals("error")) {
			try {					
				JSONObject json = (JSONObject) new JSONParser().parse(response);
				JSONObject toptracks = (JSONObject) json.get("toptracks");

				Object tracks = toptracks.get("track");	
				if (tracks == null) {
					return rec_track;
				}
				else if (tracks instanceof JSONObject) {
					this.addTrack(rec_track, tracks);
				}
				else {
					for (Object obj : (JSONArray)tracks) {
						this.addTrack(rec_track, obj);
					}
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return rec_track;
	}

	private void addTrack(List<Track> rec_track, Object obj) {
		JSONObject json_obj = (JSONObject) obj;
		JSONObject artist = (JSONObject) json_obj.get("artist");

		String track_name = (String) json_obj.get("name");
		String track_artist = (String) artist.get("name");		
		Track track = new Track(track_name, track_artist);

		rec_track.add(track);
	}

}
